<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useStore } from 'vuex'
import { ElForm, ElFormItem, ElInput, ElButton, ElSelect, ElOption, ElMessage, ElAlert } from 'element-plus'

const store = useStore()
const form = ref({
  classroomLocation: '',
  studentName: ''
})

const loading = ref(false)
const rules = {
  classroomLocation: [
    { required: true, message: '请选择教室位置', trigger: 'change' }
  ],
  studentName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 20, message: '姓名长度在 1 到 20 个字符', trigger: 'blur' }
  ]
}

const activeSession = computed(() => store.state.activeSession)
const isSignInInProgress = computed(() => store.getters.isSignInInProgress)
const signInStatus = computed(() => store.state.signInStatus)

// 用于跟踪上一次的签到状态，以便检测状态变化
const previousSignInStatus = ref(false)

// 页面加载时初始化，不自动查询活动会话
onMounted(() => {
  // 等待学生选择教室后再查询活动会话
})

// 监听签到状态变化，显示消息
watch(() => signInStatus.value.success, (newValue) => {
  if (newValue !== null) {
    if (newValue) {
      ElMessage.success(signInStatus.value.message || '签到成功！')
    } else if (signInStatus.value.message) {
      ElMessage.error(signInStatus.value.message)
    }
    // 3秒后清除状态
    setTimeout(() => {
      store.commit('CLEAR_SIGN_IN_STATUS')
    }, 3000)
  }
})

// 监听教室选择变化，查询对应教室的活动会话
watch(() => form.value.classroomLocation, (newClassroom) => {
  if (newClassroom) {
    // 将当前选择的教室存储在window对象中，供store在处理WebSocket消息时使用
    window.currentSelectedClassroom = newClassroom
    store.dispatch('queryActiveSessionByClassroom', newClassroom)
    // 重置之前的签到状态，避免切换教室时触发错误的状态变化提示
    previousSignInStatus.value = false
  }
})

// 监听签到进行状态的变化，显示状态变化提示
watch(isSignInInProgress, (newStatus, oldStatus) => {
  // 只有当学生已经选择了教室时才显示提示
  if (form.value.classroomLocation) {
    if (newStatus && !oldStatus) {
      // 签到开始
      ElMessage.success(`您选择的教室 ${form.value.classroomLocation} 签到已开始，请及时签到！`)
    } else if (!newStatus && oldStatus && activeSession.value) {
      // 签到结束
      ElMessage.warning(`您选择的教室 ${form.value.classroomLocation} 签到已结束！`)
    }
  }
  // 更新之前的签到状态
  previousSignInStatus.value = newStatus
})

const handleSignIn = async () => {
  if (!form.value.classroomLocation) {
    ElMessage.warning('请先选择教室')
    return
  }

  // 查询所选教室的最新活动会话
  await store.dispatch('queryActiveSessionByClassroom', form.value.classroomLocation)

  if (!isSignInInProgress.value) {
    ElMessage.warning('您选择的教室当前没有进行中的签到，请等待老师开始签到')
    return
  }

  // 检查学生选择的教室是否与当前签到会话的教室匹配
  if (activeSession.value && form.value.classroomLocation !== activeSession.value.classroom) {
    ElMessage.error('您选择的教室没有开放签到，请选择正确的教室')
    return
  }

  loading.value = true
  try {
    await store.dispatch('studentSignIn', {
      sessionId: activeSession.value.id,
      data: {
        studentName: form.value.studentName,
        classroomLocation: form.value.classroomLocation
      }
    })
    
    // 签到成功后清空表单
    if (signInStatus.value.success) {
      form.value.studentName = ''
    }
  } catch (error) {
    ElMessage.error('签到失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="container">
    <div class="page-header">
      <h2>学生签到</h2>
    </div>
    
    <div class="card" style="max-width: 500px; margin: 0 auto;">
      <!-- 签到状态提示 -->
      <div v-if="!isSignInInProgress" style="margin-bottom: 20px;">
        <ElAlert
          v-if="activeSession"
          title="签到尚未开始"
          type="warning"
          description="请等待老师开始签到"
          show-icon
        />
        <ElAlert
          v-else
          title="当前没有签到活动"
          type="info"
          description="请联系老师开始签到"
          show-icon
        />
      </div>
      
      <!-- 签到表单 -->
      <ElForm :model="form" :rules="rules" ref="formRef" label-width="100px">
        <ElFormItem label="教室位置" prop="classroomLocation">
          <ElSelect v-model="form.classroomLocation" placeholder="请选择教室位置">
            <ElOption label="东微机室" value="东微机室" />
            <ElOption label="西微机室" value="西微机室" />
          </ElSelect>
        </ElFormItem>
        
        <ElFormItem label="学生姓名" prop="studentName">
          <ElInput v-model="form.studentName" placeholder="请输入您的姓名" />
        </ElFormItem>
        
        <ElFormItem>
          <ElButton 
            type="primary" 
            :loading="loading" 
            @click="handleSignIn"
            :disabled="!isSignInInProgress"
            style="width: 100%"
          >
            {{ isSignInInProgress ? '点击签到' : '等待签到开始' }}
          </ElButton>
        </ElFormItem>
      </ElForm>
      
      <!-- 签到成功提示 -->
      <div v-if="signInStatus.success" style="margin-top: 20px;">
        <ElAlert
          title="签到成功"
          type="success"
          description="感谢您的签到，请遵守课堂纪律"
          show-icon
        />
      </div>
      
      <!-- 签到失败提示 -->
      <div v-else-if="signInStatus.message && !signInStatus.success" style="margin-top: 20px;">
        <ElAlert
          title="签到失败"
          type="error"
          :description="signInStatus.message"
          show-icon
        />
      </div>
    </div>
    
    <!-- 当前签到信息 -->
    <div v-if="activeSession" class="card" style="max-width: 500px; margin: 30px auto 0;">
      <h3>当前签到信息</h3>
      <p><strong>班级：</strong>{{ activeSession.className }}</p>
      <p><strong>节次：</strong>{{ activeSession.sectionNumber }}</p>
      <p><strong>课题：</strong>{{ activeSession.topic }}</p>
      <p><strong>教师：</strong>{{ activeSession.teacherName }}</p>
      <p><strong>教室：</strong>{{ activeSession.classroom }}</p>
      <p><strong>状态：</strong>{{ isSignInInProgress ? '签到进行中' : '签到未开始' }}</p>
    </div>
  </div>
</template>

<style scoped>
.card {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>